package com.dragon.aipictures.Controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.aipictures.Exception.BusinessException;
import com.dragon.aipictures.Exception.StateCode;
import com.dragon.aipictures.annotation.AuthCheck;
import com.dragon.aipictures.api.aliyunai.model.AliYunAiApi;
import com.dragon.aipictures.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.dragon.aipictures.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.dragon.aipictures.api.imageSearch.ImageSearchApiFacade;
import com.dragon.aipictures.api.imageSearch.ImageSearchResult;
import com.dragon.aipictures.common.BaseResponse;
import com.dragon.aipictures.constant.UserConstant;
import com.dragon.aipictures.domain.Enum.PictureReviewStatusEnum;
import com.dragon.aipictures.domain.dto.request.*;
import com.dragon.aipictures.domain.dto.request.spaceUser.SpaceUserDeleteRequest;
import com.dragon.aipictures.domain.entity.Picture;
import com.dragon.aipictures.domain.entity.Space;
import com.dragon.aipictures.domain.entity.User;
import com.dragon.aipictures.domain.vo.picture.PictureVO;
import com.dragon.aipictures.manager.auth.SpaceUserAuthManager;
import com.dragon.aipictures.manager.auth.annotation.SaSpaceCheckPermission;
import com.dragon.aipictures.manager.auth.model.SpaceUserPermissionConstant;
import com.dragon.aipictures.service.pictureService;
import com.dragon.aipictures.service.spaceService;
import com.dragon.aipictures.service.userService;
import com.dragon.aipictures.util.ResultUtils;
import com.dragon.aipictures.util.ThrowUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {





    @Resource
    private userService userService;
    @Resource
    private pictureService pictureService;
    @Resource
    private spaceService spaceService;
    @Resource
    private AliYunAiApi aliYunAiApi;
    @Resource
    SpaceUserAuthManager spaceUserAuthManager;
    /**
     * 测试文件上传
     *
     * @param multipartFile
     * @return
     */

    /**
     * 通过文件上传图片
     */
    @PostMapping("/upload/file")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureVO> uploadPictureByFile(
            @RequestPart("file") MultipartFile multipartFile,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 通过url上传图片
     */
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
            HttpServletRequest request
    ) {
        ThrowUtil.throwIf(pictureUploadByBatchRequest == null, StateCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }


    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest,
                                                 HttpServletRequest request) {
        ThrowUtil.throwIf(pictureReviewRequest == null, StateCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }


    /**
     * 删除图片
     */
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody SpaceUserDeleteRequest spaceUserDeleteRequest, HttpServletRequest request) {
        if (spaceUserDeleteRequest == null || spaceUserDeleteRequest.getId() <= 0) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.deletePicture(spaceUserDeleteRequest.getId(), loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 更新图片（仅管理员可用）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 数据校验
        pictureService.validPicture(picture);
        // 判断是否存在
        long id = pictureUpdateRequest.getId();
//        Long spaceId = pictureUpdateRequest.getSpaceId();

        Picture oldPicture = pictureService.getById(id);
        User loginUser = userService.getLoginUser(request);
        ThrowUtil.throwIf(oldPicture == null, StateCode.NOT_FOUND_ERROR);
//        if (spaceId==null) {
//            picture.setSpaceId(oldPicture.getSpaceId());
//        }else{
//            Long oldSpaceId = oldPicture.getSpaceId();
//            ThrowUtil.throwIf(spaceId!=oldSpaceId,StateCode.PARAMS_ERROR,"空间id不一致");
//        }
        //填充审核参数，更新也要审核
        pictureService.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = pictureService.updateById(picture);
        ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取图片（仅管理员可用）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        Long id = pictureQueryRequest.getId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        ThrowUtil.throwIf(id <= 0, StateCode.PARAMS_ERROR);
        pictureQueryRequest.setId(id);
        if(spaceId==null){
            spaceId=0L;
        }
        pictureQueryRequest.setSpaceId(spaceId);
        QueryWrapper<Picture> queryWrapper = pictureService.getQueryWrapper(pictureQueryRequest);
        // 查询数据库
        Picture picture = pictureService.getOne(queryWrapper);
//        Picture picture = pictureService.getById(queryWrapper);

        ThrowUtil.throwIf(picture == null, StateCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(picture);
    }

    /**
     * 根据 id 获取图片（封装类）
     */
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        Long id = pictureQueryRequest.getId();
        Long spaceId = pictureQueryRequest.getSpaceId();

        ThrowUtil.throwIf(id <= 0, StateCode.PARAMS_ERROR);

        pictureQueryRequest.setId(id);
        Space space=null;
        if(spaceId==null){
            pictureQueryRequest.setSpaceId(0L);
        }else{
            space = spaceService.getById(spaceId);
        }
        User loginUser = userService.getLoginUser(request);

        QueryWrapper<Picture> queryWrapper = pictureService.getQueryWrapper(pictureQueryRequest);
        Picture picture = pictureService.getOne(queryWrapper);

        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        pictureVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(pictureVO);
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        if (pictureQueryRequest.getSpaceId()==null) {
            pictureQueryRequest.setSpaceId(0L);
        }
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表（封装类）
     */
    @PostMapping("/list/page/vo")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtil.throwIf(size > 20, StateCode.PARAMS_ERROR);
        //普同用户智能查询到审核通过的照片
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
//            pictureQueryRequest.setNullSpaceId(true);
            pictureQueryRequest.setSpaceId(0L);
        } else {
            // 私有空间
            User loginUser = userService.getLoginUser(request);
            Space space = spaceService.getById(spaceId);
            ThrowUtil.throwIf(space == null, StateCode.NOT_FOUND_ERROR, "空间不存在");
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(StateCode.NO_AUTH_ERROR, "没有空间权限");
            }
        }

        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

    /**
     * 编辑图片（给用户使用）
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.editPicture(pictureEditRequest, loginUser);
        return ResultUtils.success(true);
    }


    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                      HttpServletRequest request) {
        Page<PictureVO> pictureVOPage = pictureService.listPictureVOByPageWithCache(pictureQueryRequest, request);

        // 返回结果
        return ResultUtils.success(pictureVOPage);
    }


    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Boolean> updatePictureVOByPageWithCache(@RequestBody PictureUpdateRequest pictureUpdateRequest,
                                                                      HttpServletRequest request) {
        Boolean rs = pictureService.updatePictureVOByPageWithCache(pictureUpdateRequest, request);
        return ResultUtils.success(rs);
    }
    /**
     * 以图搜图
     */
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPictureByBaidu(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
//       这里考虑给图片表再加一个字段，表示原图的后缀，或者直接让用户传，判断用户的后缀是否符合百度的要求，然后再调baidu的接口
        ThrowUtil.throwIf(searchPictureByPictureRequest == null, StateCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtil.throwIf(pictureId == null || pictureId <= 0, StateCode.PARAMS_ERROR);
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtil.throwIf(oldPicture == null, StateCode.NOT_FOUND_ERROR);
        String originUrl = oldPicture.getUrl();
        String suffix = FileUtil.getSuffix(originUrl);
        //将图片中的web
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(originUrl);
        return ResultUtils.success(resultList);
    }
    @PostMapping("/search/color")
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest, HttpServletRequest request) {
        ThrowUtil.throwIf(searchPictureByColorRequest == null, StateCode.PARAMS_ERROR);
        String picColor = searchPictureByColorRequest.getPicColor();
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        User loginUser = userService.getLoginUser(request);
        List<PictureVO> result = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(result);
    }
    @PostMapping("/edit/batch")
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        ThrowUtil.throwIf(pictureEditByBatchRequest == null, StateCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
        return ResultUtils.success(true);
    }
    /**
     * 创建 AI 扩图任务
     */
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(
            @RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
            HttpServletRequest request) {
        if (createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        CreateOutPaintingTaskResponse response = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 扩图任务
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        ThrowUtil.throwIf(StrUtil.isBlank(taskId), StateCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(task);
    }




}
